package coreservlets;

import java.util.concurrent.*;

// In older Java implementations, this would usually give the right answer
// where all currentThreadNums were unique, but would still sometimes
// give the wrong answer where some currentThreadNums were repeated.
// On newer Java implementations and faster computers where threads have
// much smaller times slices and the system is more aggressive about
// switching threads when one is doing IO, the error shows 
// up almost all the time. In that case, see RaceConditionsTest2, where
// the error still shows up only once in a while.

public class RaceConditionsApp implements Runnable {
  private final static int LOOP_LIMIT = 5;
  private final static int POOL_SIZE = 10;
  private int latestThreadNum = 0;
  
  public RaceConditionsApp() {
    ExecutorService taskList;
    taskList = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i=0; i<POOL_SIZE; i++) {
      taskList.execute(this);
    }
  }
  
  public void run() {
    int currentThreadNum = latestThreadNum;
    System.out.println("Set currentThreadNum to " + currentThreadNum);
    latestThreadNum = latestThreadNum + 1;
    for (int i=0; i<LOOP_LIMIT; i++) {
      doSomethingWith(currentThreadNum);
    }
  }
  
  private void doSomethingWith(int threadNumber) {
    // Blah blah
  }
}
